import React, { ReactNode } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableWithoutFeedback,
  Keyboard,
  StyleProp,
  TextStyle
} from 'react-native';
import { WIDTH, PRIMARY_COLOR, TITLE_COLOR, ONE_PIXEL } from './config';
import Touchable from 'react-native-platform-touchable';
import Modal from './Modal';

export type Button = {
  title?: string;
  color?: string;
  onPress?: Function | 'nohide';
  [key: string]: any;
};

export interface ConfirmProps {
  buttons?: Button[];
  title?: string;
  titleStyle?: StyleProp<TextStyle>;
  message?: ReactNode;
  messageStyle?: StyleProp<TextStyle>;
  style?: any;
  backCancelable?: boolean;
  maskClosable?: boolean; // 是否允许点击蒙层关闭弹窗
  destroy?: () => void;
}

interface State {
  showing: boolean;
}

export default class Confirm extends React.Component<ConfirmProps, State> {
  static displayName = 'Confirm';

  static defaultProps = {
    buttons: [{ title: '确定', color: PRIMARY_COLOR, onPress: () => {} }],
    title: '提示',
    message: '',
    backCancelable: true,
    maskClosable: false
  };

  state: State = {
    showing: true
  };

  hide = () => {
    Keyboard.dismiss();
    this.setState({ showing: false });
  };

  _onCancel = () => {
    this.props.backCancelable && this.hide();
  };

  _onPressMask = () => {
    this.props.maskClosable && this.hide();
  };

  render() {
    const {
      buttons,
      title,
      titleStyle,
      message,
      messageStyle,
      style
    } = this.props;
    const { showing } = this.state;
    return (
      <Modal
        renderToHardwareTextureAndroid={true}
        transparent={true}
        visible={showing}
        statusBarTranslucent={true}
        onRequestClose={this._onCancel}
        onBackdropPress={this._onPressMask}
        onHide={() => {
          setTimeout(() => this.props.destroy?.(), 100);
        }}
        supportedOrientations={['landscape', 'portrait']}
      >
        <View style={[styles.wrapper, style]}>
          <Text
            numberOfLines={1}
            ellipsizeMode="tail"
            style={[styles.title, titleStyle]}
          >
            {title}
          </Text>
          {Boolean(message) &&
            (typeof message === 'string' ? (
              <Text style={[styles.message, messageStyle]}>{message}</Text>
            ) : (
              message
            ))}
          <View style={styles.buttonContainer}>
            {buttons.map((item, index) => {
              return (
                <Touchable
                  style={[
                    styles.button,
                    {
                      borderRightWidth:
                        index < buttons.length - 1
                          ? StyleSheet.hairlineWidth
                          : 0,
                      borderRightColor: '#E5E5E5'
                    }
                  ]}
                  key={index}
                  onPress={async () => {
                    const ret = await (item.onPress instanceof Function &&
                      item.onPress?.());
                    if (ret !== 'nohide') this.hide();
                  }}
                  background={Touchable.Ripple(item.color, true)}
                >
                  <Text
                    style={[
                      styles.buttonText,
                      {
                        color: item.color || '#9A9A96',
                        fontWeight: item.fontWeight
                      },
                      item.textStyle
                    ]}
                  >
                    {item.title}
                  </Text>
                </Touchable>
              );
            })}
          </View>
        </View>
      </Modal>
    );
  }
}

const styles = StyleSheet.create({
  wrapper: {
    overflow: 'hidden',
    borderRadius: 16,
    width: WIDTH - 48,
    backgroundColor: 'white'
  },
  title: {
    textAlign: 'center',
    fontSize: 17,
    color: TITLE_COLOR,
    fontWeight: 'bold',
    marginTop: 20,
    marginHorizontal: 18
  },
  message: {
    lineHeight: 20,
    textAlign: 'center',
    fontSize: 15,
    color: '#5D6E7F',
    marginTop: 20,
    marginHorizontal: 18
  },
  buttonContainer: {
    marginTop: 20,
    backgroundColor: 'white',
    height: 50,
    flexDirection: 'row',
    alignItems: 'stretch',
    borderTopColor: '#E5E5E5',
    borderTopWidth: StyleSheet.hairlineWidth
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  buttonText: {
    fontSize: 17,
    fontWeight: 'bold',
    textAlign: 'center',
    textAlignVertical: 'center'
  }
});
